<template>
  <div>
    <el-upload
      class="upload-demo"
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-change="onChange"
      :on-success="onSuccess"
      :on-error="onError"
      :before-remove="beforeRemove"
      :multiple="false"
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList">
      <el-button size="small" ><i class="el-icon-upload2"></i><span class="upload-btn-text">上 传</span></el-button>
      <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
    </el-upload>
    <el-dialog :title="title" :visible.sync="dialogVisible">
      <img width="100%" :src="imageUrl" alt="title">
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        fileList: [],
        title: '',
        imageUrl: '',
        dialogVisible: false
      };
    },
    methods: {
      handleRemove(file, fileList) {
        this.$message('文件已删除');
      },
      handlePreview(file) {
        this.title = file.name;
        this.dialogVisible = true;
      },
      handleExceed(files, fileList) {
        this.$message.warning(`如需更改，请先删除文件后再次上传`);
      },
      onChange(file) {
        let url = ''

        if (window['createObjcectURL'] != undefined) {
          url = window['createObjcectURL'](file.raw)
        } else if (window['URL'] != undefined) {
          url = window['URL'].createObjectURL(file.raw)
        } else if (window['webkitURL'] != undefined) {
          url = window['webkitURL'].createObjectURL(file.raw)
        }
        this.imageUrl = url
      },
      onSuccess(file) {
        this.$message.success('上传成功！');
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      onError(file) {
        console.log(file);
        this.$message.error('上传失败！');
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      }
    }
  }
</script>
<style lang="scss" scoped>
.upload-btn-text{
  margin-left: 10px!important;
}
</style>
